import { onMounted, onUnmounted, ref, Ref } from 'vue'

function useEventListener<T extends Event = Event>(
  target: Ref<HTMLElement | null> | HTMLElement | Window,
  event: string,
  handler: (event: T) => void,
  rightNow: boolean = false
) {
  // 如果 target 是一个 ref，则需要解包它的值
  const targetRef = ref(target) as Ref<HTMLElement | Window | null>

  if (rightNow) {
    // 确保 target 不是 null 并且存在 addEventListener 方法
    const element =
      targetRef.value instanceof Window
        ? targetRef.value
        : (targetRef.value as HTMLElement)
    element?.addEventListener(event, handler as EventListener)
  } else {
    onMounted(() => {
      // 确保 target 不是 null 并且存在 addEventListener 方法
      const element =
        targetRef.value instanceof Window
          ? targetRef.value
          : (targetRef.value as HTMLElement)
      element?.addEventListener(event, handler as EventListener)
    })
  }

  onUnmounted(() => {
    // 确保 target 不是 null 并且存在 removeEventListener 方法
    const element =
      targetRef.value instanceof Window
        ? targetRef.value
        : (targetRef.value as HTMLElement)
    element?.removeEventListener(event, handler as EventListener)
  })
}

export default useEventListener
